package org.ldh.web.filter;

import org.ldh.domain.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter("*.action") //拦截所有以action结尾的请求
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("--------loginFilter--------");

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpSession session = request.getSession();

        //获取登录后保存在session中的用户信息
        User session_user = (User) session.getAttribute("session_user");
        System.out.println(session_user);

        if(session_user != null){
            //放行
            filterChain.doFilter(request, servletResponse);
        }else {
            //存储错误信息到request域
            request.setAttribute("login_error","您尚未登录！请先登录");
            //跳转登录页面
            request.getRequestDispatcher("index.jsp").forward(request,servletResponse);
        }
    }

    @Override
    public void destroy() {

    }
}
